<?php
class Upload {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 上传文件
     */
    public function upload(): void {
        try {
            // 检查管理员权限
            $token = $this->auth->getBearerToken();
            $admin = $this->auth->validateToken($token, 'admin');

            if (empty($_FILES['file'])) {
                throw new Exception("请选择上传文件", 400);
            }

            $file = $_FILES['file'];
            
            // 验证文件上传是否成功
            if ($file['error'] !== UPLOAD_ERR_OK) {
                throw new Exception($this->getUploadError($file['error']), 400);
            }

            // 验证文件类型
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!in_array($file['type'], $allowedTypes)) {
                throw new Exception("只允许上传图片文件(jpg,png,gif,webp)", 400);
            }

            // 验证文件大小 (限制5MB)
            if ($file['size'] > 5 * 1024 * 1024) {
                throw new Exception("文件大小不能超过5MB", 400);
            }

            // 创建上传目录
            $uploadDir = $this->getUploadDir();
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            // 生成唯一文件名
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $newFilename = uniqid() . '.' . strtolower($ext);
            $relativePath = $this->getRelativePath() . '/' . $newFilename;
            $fullPath = $uploadDir . '/' . $newFilename;

            // 移动文件
            if (!move_uploaded_file($file['tmp_name'], $fullPath)) {
                throw new Exception("文件保存失败", 500);
            }

            // 记录到数据库
            $stmt = $this->conn->prepare("
                INSERT INTO attachments (
                    admin_id, file_name, file_path, file_size, file_type, created_at
                ) VALUES (
                    :admin_id, :file_name, :file_path, :file_size, :file_type, :created_at
                )
            ");
            $stmt->execute([
                ':admin_id' => $admin['id'],
                ':file_name' => $file['name'],
                ':file_path' => $relativePath,
                ':file_size' => $file['size'],
                ':file_type' => $file['type'],
                ':created_at' => time()
            ]);

            $fileId = $this->conn->lastInsertId();

            // 返回完整URL路径
            $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
            $fileUrl = $baseUrl . $relativePath;

            echo json_encode([
                'code' => 200,
                'msg' => '上传成功',
                'data' => [
                    'id' => $fileId,
                    'url' => $fileUrl,
                    'path' => $relativePath,
                    'name' => $file['name'],
                    'size' => $file['size'],
                    'type' => $file['type']
                ]
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 获取文件列表 (分页)
     */
   public function list(): void {
    try {
        // 检查管理员权限
        $token = $this->auth->getBearerToken();
        $admin = $this->auth->validateToken($token, 'admin');

        $pagination = new Pagination($this->conn);
        $result = $pagination->paginate(
            "SELECT * FROM attachments WHERE admin_id = :admin_id ORDER BY created_at DESC",
            [':admin_id' => $admin['id']],
            "attachments",
            "admin_id = :admin_id",
            [':admin_id' => $admin['id']]
        );

        // 添加完整URL
        $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
        foreach ($result['list'] as &$item) {
            $item['url'] = $baseUrl . $item['file_path'];
        }

        echo json_encode([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $result  // 直接返回$result，不要额外嵌套
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'code' => $e->getCode() ?: 500,
            'msg' => $e->getMessage(),
            'data' => null
        ]);
    }
}

    /**
     * 获取上传目录
     */
    private function getUploadDir(): string {
        $yearMonth = date('Y-m');
        return __DIR__ . '/../../api/attachment/' . $yearMonth;
    }

    /**
     * 获取相对路径
     */
    private function getRelativePath(): string {
        $yearMonth = date('Y-m');
        return '/api/attachment/' . $yearMonth;
    }

    /**
     * 获取上传错误信息
     */
    private function getUploadError(int $errorCode): string {
        $errors = [
            UPLOAD_ERR_INI_SIZE => '文件大小超过服务器限制',
            UPLOAD_ERR_FORM_SIZE => '文件大小超过表单限制',
            UPLOAD_ERR_PARTIAL => '文件只有部分被上传',
            UPLOAD_ERR_NO_FILE => '没有文件被上传',
            UPLOAD_ERR_NO_TMP_DIR => '找不到临时文件夹',
            UPLOAD_ERR_CANT_WRITE => '文件写入失败',
            UPLOAD_ERR_EXTENSION => '上传被PHP扩展阻止'
        ];
        return $errors[$errorCode] ?? '未知上传错误';
    }
  
}